package cn.bingoo.handy;

public class SeedsStringParser {
    boolean rangeDetected = false;
    StringBuilder sb = new StringBuilder();

    private void appendChar(char c) {
        if (!rangeDetected) {
            sb.append(c);
        }
        else {
            rangeDetected = false;
            if (sb.length() > 0) {
                for (char from = (char) (sb.charAt(sb.length() - 1) + 1); from <= c; ++from) {
                    sb.append(from);
                }
            }
        }
    }

    public static void main(String[] args) {
        String parse = new SeedsStringParser().parse("0-3");
        System.out.println(parse);

        parse = new SeedsStringParser().parse("0\\-3");
        System.out.println(parse);
        parse = new SeedsStringParser().parse("\\u4e00-\\u9fa5");
        System.out.println(parse);

        parse = new SeedsStringParser().parse("0-9a-zA-Z~!@#$%^&*()=\\-_+");
        System.out.println(parse);
    }

    public String parse(String seeds) {
        int len = seeds.length();
        char[] charArray = seeds.toCharArray();
        for (int i = 0; i < len; ++i) {
            char ch = charArray[i];
            switch (ch) {
            case '\\':
                if (i + 1 < charArray.length) {
                    char nch = charArray[i + 1];
                    if (nch == 'u' || nch == 'U') {
                        if (i + 5 < charArray.length) {
                            char c1 = charArray[i + 2];
                            char c2 = charArray[i + 3];
                            char c3 = charArray[i + 4];
                            char c4 = charArray[i + 5];
                            if (Character.isLetterOrDigit(c1) && Character.isLetterOrDigit(c2)
                                    && Character.isLetterOrDigit(c3) && Character.isLetterOrDigit(c4)) {
                                appendChar((char) Integer.parseInt("" + c1 + c2 + c3 + c4, 16));
                                i += 5;
                                continue;
                            }
                        }
                    }
                    ++i;
                    appendChar(nch);
                }
                else {
                    appendChar('\\');
                }
                break;
            case '-':
                if (!rangeDetected) {
                    rangeDetected = true;
                }
                else {
                    appendChar('-');
                }
                break;
            default:
                appendChar(ch);
                break;
            }
        }

        return sb.toString();
    }
}
